<template>
  <div id="warp">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/manage' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统权限</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="w">
      <el-card :body-style="{padding: '0'}" shadow="hover" class="nav">
        <div class="top"><p>所有角色</p></div>
        <div class="add">
          <el-button size="mini" plain @click="addRoles"><i class="el-icon-plus"></i>添加角色</el-button>
        </div>
        <ul>
          <el-tooltip v-for="role in roles" :key="role.id" placement="right">
            <div slot="content">
              添加人：{{role.userId}}
            </div>
            <li @click="roleDetail(role.id, role.name, role.description, role.type)" class="roleList">
              <p class="name">{{role.name}}</p>
              <p class="des">{{role.description}}</p>
              <ul class="do">
                <li>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    @click.stop="deleteRole(role.id)">
                  </el-button>
                </li>
              </ul>
            </li>
          </el-tooltip>
        </ul>
      </el-card>
      <div class="tree">
        <div class="addInput" v-show="addInputShow">
          <el-form :inline="true" :model="formRole" class="demo-form-inline" ref="formRole1">
            <el-form-item label="角色名" prop="name">
              <el-input v-model="formRole.name" placeholder="角色名"/>
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input v-model="formRole.description" placeholder="描述"/>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="formRole.type">
                <el-radio :label="1">自定义角色</el-radio>
                <el-radio :label="2">官方角色</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div class="title">所有权限</div>
        <el-tree
          :data="treeData"
          empty-text="暂无数据"
          :props="defaultProps"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          @check="checkChange">
        </el-tree>
        <div class="subBtn">
          <el-button v-show="subAddBtnShow" type="primary" size="medium" :disabled="disabled" @click="submitAdd">添加</el-button>
          <el-button v-show="subUpdateBtnShow" type="primary" size="medium" :disabled="disabled" @click="submitUpdate">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data () {
    return {
      url: {
        roleAdd: '/admin/manager/permission/matrix/role/add',
        roleUpdate: '/admin/manager/permission/matrix/role/update'
      },
      roles: [],
      treeData: [],
      defaultKeys: [],
      defaultProps: {
        label: 'name'
      },
      formRole: {
        name: '',
        description: '',
        type: 1
      },
      updateRole: {
        userRole: {
          id: 0,
          name: '',
          description: ''
        },
        updateRole: false,
        updatePermission: false,
        adds: [],
        removes: []
        // 是否修改权限
      },
      addInputShow: false,
      subAddBtnShow: false,
      subUpdateBtnShow: false,
      disabled: true,
      isChange: false,
      oldData: {},
      oldPerData: [],
      oldPerObj: [],
      newPerData: [],
      newPerObj: []
    }
  },
  methods: {
    checkChange (data, {checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys}) {
      if (this.disabled) {
        this.disabled = false
      }
      if (!this.subBtnShow) {
        this.subBtnShow = true
      }
      this.isChange = true
      this.oldData.change = true
      this.newPerObj = checkedNodes
    },
    addRoles () {
      this.addInputShow = true
      this.subAddBtnShow = true
      this.subUpdateBtnShow = false
      this.disabled = false
      this.$refs.tree.setCheckedKeys([])
      this.$refs.formRole1.resetFields()
    },
    roleDetail (id, name, des, type) {
      this.addInputShow = true
      this.subUpdateBtnShow = true
      this.subAddBtnShow = false
      this.disabled = false
      this.updateRole.userRole.id = id
      this.formRole.name = name
      this.formRole.description = des
      this.formRole.type = type
      this.oldData = JSON.parse(JSON.stringify(this.formRole))
      this.oldData.change = false
      this.getRolePermission(id)
    },
    submitAdd () {
      let params = {
        userRole: {},
        adds: []
      }
      if (this.formRole.name !== '') {
        params.userRole = JSON.parse(JSON.stringify(this.formRole))
        if (this.formRole.description === '') {
          params.userRole.description = '无'
        }
        if (this.isChange) {
          this.newPerObj.forEach((item, index) => {
            if (!item.children) {
              params.adds.push(item.id)
            }
          })
        }
        params.addPermission = this.isChange
      } else {
        return
      }
      this.$ajax.post(this.url.roleAdd, JSON.stringify(params)).then((res) => {
        console.log(res)
        if (res.data.success) {
          this.getRolesList()
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          document.querySelector('main').scrollTop = 0
        }
      })
    },
    submitUpdate () {
      // 获取数据
      if (this.oldData.name !== this.formRole.name || this.oldData.description !== this.formRole.description) {
        this.updateRole.updateRole = true
        this.updateRole.userRole.name = this.formRole.name
        this.updateRole.userRole.description = this.formRole.description
      }
      if (this.isChange) {
        this.newPerObj.forEach((item, index) => {
          if (!item.children) {
            this.newPerData[item.id] = item.id
          }
        })
        if (!this.oldPerObj[0]) {
          this.arrUtil(this.newPerData)
          this.updateRole.adds = this.newPerData
        } else {
          this.oldPerObj.forEach((oldItem, oldIndex) => {
            this.oldPerData[oldItem] = oldItem
          })
          for (let i = 0; i < this.newPerData.length; i++) {
            if (this.oldPerData[i] === this.newPerData[i]) {
              this.oldPerData.splice(i, 1)
              this.newPerData.splice(i, 1)
              i--
            }
          }
          this.arrUtil(this.oldPerData)
          this.arrUtil(this.newPerData)
          this.updateRole.adds = this.newPerData
          this.updateRole.removes = this.oldPerData
        }
        if (this.updateRole.adds[0] || this.updateRole.removes[0]) {
          this.updateRole.updatePermission = true
        }
      }
      // branch matrix
      this.$ajax.post(this.url.roleUpdate, JSON.stringify(this.updateRole)).then((res) => {
        if (res.data.success) {
          let id = this.updateRole.userRole.id
          if (this.updateRole.updateRole) {
            this.getRolesList()
            this.oldData = JSON.parse(JSON.stringify(this.formRole))
            this.oldData.change = false
          }
          this.updateRole.adds = []
          this.updateRole.removes = []
          this.oldPerData = []
          this.newPerData = []
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.getRolePermission(id)
        }
      })
    },
    deleteRole (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // branch matrix
        this.$ajax.post('/admin/manager/permission/role/delete', id).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getRolesList()
        }).catch((err) => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // branch/role/list matrix/role/list
    getRolesList () {
      this.$ajax.post('/admin/manager/permission/role/list').then((res) => {
        this.roles = res.data.data
      })
    },
    getRolePermission (id) {
      // branch matrix
      this.$ajax.post('/admin/manager/permission/role/permission/ids', JSON.stringify(id)).then((res) => {
        this.oldPerObj = JSON.parse(JSON.stringify(res.data.data))
        this.$refs.tree.setCheckedKeys(res.data.data)
      })
    },
    loadMore () {
      // branch matrix
      this.$ajax.post('/admin/manager/permission/matrix/set/list').then((res) => {
        let sets = []
        res.data.data.sets.forEach((item, index) => {
          sets[item.id] = item
          sets[item.id].children = []
          item.id += 1000
          item.name += '(' + item.description + ')'
        })
        let unBelong = []
        res.data.data.childrens.forEach((item, index) => {
          item.name += '(' + item.description + ')'
          if (item.permissionSetId === 0) {
            unBelong.push(item)
          }
          if (sets[item.permissionSetId]) {
            sets[item.permissionSetId].children.push(item)
          }
        })
        this.arrUtil(sets)
        if (unBelong[0]) {
          sets.push({
            name: '未关联权限',
            children: [...unBelong]
          })
        }
        this.treeData = sets
      })
    },
    arrUtil (arr) {
      for (let i = 0; i < arr.length; i++) {
        if (typeof arr[i] === 'undefined' || arr[i] === '') {
          arr.splice(i, 1)
          i--
        }
      }
    }
  },
  created () {
    this.getRolesList()
    this.loadMore()
  }
}
</script>

<style scoped>
  .w{
    overflow: hidden;
  }
  .nav{
    width: 18%;
    height: 100%;
    float: left;
    border: 1px solid #DCDFE6;
    box-sizing: border-box;
  }
  .roleList{
    position: relative;
    border-top: 1px solid #DCDFE6;
    padding: 10px 15px;
    cursor: pointer;
  }
  .roleList:hover{
    background-color: #EBEEF5;
  }
  .roleList:hover .do{
    display: block;
  }
  .nav li p{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .nav li .name{
    font-size: 16px;
    color: #303133;
    line-height: 30px;
    font-weight: 600;
  }
  .nav li .des{
    font-size: 12px;
    color: #606266;
    line-height: 25px;
  }
  .top{
    font-weight: bold;
    font-size: 16px;
    line-height: 25px;
    padding: 10px;
    color: #fff;
    background-color: #409EFF;
  }
  .add{
    padding: 10px 0;
    text-align: center;
  }
  .title{
    background-color: #409EFF;
    padding: 10px;
    border-radius: 5px 5px 0 0;
    color: #fff;
  }
  .tree{
    width: 80%;
    float: left;
    margin-left: 2%;
    /*border: 1px solid #DCDFE6;*/
    /*box-sizing: border-box;*/
  }
  .subBtn{
    background-color: #fff;
    text-align: center;
    padding: 10px;
  }
  .do{
    position: absolute;
    top: 10px;
    right: 10px;
    display: none;
  }
</style>
